/**
 * 通用的路由跳转文件
 */
const routerPath = {
    'index': '/pages/index/index',
    'pay': '/pages/pay/index',
    'activity': '/pages/activity/index'
}

module.exports = {


    // this.$route.push('index')
    // this.$route.push({
    //     path: 'index',
    //     query: {
    //         userId: 123
    //     }
    // })

    push(path, option = {}) {
        if (typeof path == 'string') {
            option.path = path
        } else {
            option = path
        }

        let url = routerPath[option.path]

        // openType:
        // wx.reLaunch 关闭所有页面，打开到应用内的某个页面
        // wx.redirectTo 关闭当前页面，跳转到应用内的某个页面
        // wx.navigateTo 保留当前页面，跳转到应用内的某个页面
        // wx.nabigeteBack 关闭当前页面，返回上一页或多级页面

        // duration跳转延迟
        let { query = {}, openType, duration } = option

        let params = this.parse(query)
        if (params) {
            url += '?' + params
        }


        duration ? setTimeout(() => {
            this.to(openType, url)
        }, duration) : this.to(openType, url)
    },
    /**
     * 对象转换成地址栏格式
     * @param data
     * @returns {string}
     */
    parse(data) {
        let arr = []
        // 把对象转换成数组
        for (let key in data) {
            arr.push(key + '=' + data[key])
        }

        // 把数组转换成a=1&b=2的格式
        return arr.join('&')
    },
    to(openType, url) {
        let obj = { url }
        if (openType == 'redirect') {
            wx.redirectTo(obj)
        } else if (openType == 'reLaunch') {
            wx.reLaunch(obj)
        } else if (openType == 'back') {
            wx.nabigateBack({
                delta: 1
            })
        } else {
            wx.navigateTo(obj)
        }
    }
}